﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BattleShips.Common;
using TestServer;

namespace BattleShips.GameServers.CommandRunners {
    class SearchForARoom : ICommandRunner {
        public string RunCommand(Command command, TestServer.GameClient client, TestServer.GameServer server) {
            Dictionary<uint, GameRoom> rooms = new Dictionary<uint, GameRoom>();
            List<GameClient> waitingPlayers = new List<GameClient>();
            List<int> indexSearched = new List<int>();
            rooms = server.GetRooms();
            waitingPlayers = server.GetWaitingPlayers();

            if (rooms.Count == 0) {
                return "error:0";
            }

            string gameRoomToJoin = string.Empty;
            int tryToConnect = -1;
            int index = 9999999;
            do {
                Random r = new Random();
                indexSearched.Add(index);
                index = r.Next(waitingPlayers.Count);
                if (!indexSearched.Contains(index)) {
                    GameClient randomGameClient = waitingPlayers[index];
                    if (randomGameClient != null) {
                        if (!rooms[randomGameClient.IdPlayer].FreeSlot()) {
                            tryToConnect++;
                            if (tryToConnect == waitingPlayers.Count - 1) {
                                return "No room found. Please try again.";
                            }
                        } else {
                            server.Join(randomGameClient.IdPlayer, client);
                            server.OpponentFound(randomGameClient.IdPlayer, randomGameClient,client);
                            tryToConnect = waitingPlayers.Count - 1;
                            gameRoomToJoin = rooms[randomGameClient.IdPlayer].RoomName;
                        }
                    }
                }
            } while (tryToConnect != waitingPlayers.Count - 1);
            return "You have join in " + gameRoomToJoin + " . ";
        }
    }
}
